package com.ph.controller.personal;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.ph.constant.PsResultEnum;
import com.ph.custom.annotation.MemberCache;
import com.ph.entity.MemberInfo;
import com.ph.shopping.common.core.customenum.ResultEnum;
import com.ph.shopping.common.core.customenum.SmsCodeType;
import com.ph.shopping.common.core.exception.BizException;
import com.ph.shopping.common.util.http.IPUtil;
import com.ph.shopping.common.util.page.PageBean;
import com.ph.shopping.common.util.result.Result;
import com.ph.shopping.facade.member.service.IMemberCashService;
import com.ph.shopping.facade.member.service.ISmsCodeSendService;
import com.ph.shopping.facade.member.vo.MemberInfoByCashVo;
import com.ph.shopping.facade.pay.service.ICashService;
import com.ph.shopping.facade.pay.vo.CashVo;
import com.ph.shopping.facade.score.request.ScorePageRequest;
import com.ph.shopping.facade.score.service.IScoreService;
import com.ph.shopping.facade.score.vo.MemberScoreVo2;
import com.ph.util.ResultUtil;

/**
 * @项目：phshopping
 * @描述：我的资产controller
 * @作者： Mr.zheng
 * @创建时间：2017-03-31
 * @Copyright @2017 by Mr.zheng
 */
@Controller
@RequestMapping("/score")
public class ScoreController {

    private static Logger logger = LoggerFactory.getLogger(ScoreController.class);

    @Reference(version = "1.0.0")
    IScoreService scoreService;
    
    @Reference(version = "1.0.0")
    private ICashService cashService;
    
    @Reference(version = "1.0.0")
    private IMemberCashService memberCashService;
    
    @Reference(version = "1.0.0")
    private ISmsCodeSendService smsCodeSendService;

    /**
     * 获取我的资产
     *
     * @author zhengpeng
     */
    @MemberCache
    @RequestMapping(value = "/list", method = {RequestMethod.GET, RequestMethod.POST})
    public String list(HttpServletRequest request, Model model,
                                 @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                 @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
                                 Map<String, Object> map,MemberInfo memberInfo) {
        try {
            PageBean pageBean =  new PageBean();
            pageBean.setPageNum(pageNum);
            pageBean.setPageSize(pageSize);
            ScorePageRequest scorePageRequest = new ScorePageRequest();
            scorePageRequest.setMemberId(memberInfo.getId());
            //查询个人用户积分
            map.put("memberScore",getMemberScore(memberInfo.getId()));
            MemberScoreVo2 memberScoreVo2 = getMemberScore(memberInfo.getId());
            map.put("enablescore",0.0);
            map.put("standbyscore",0.0);
            if (null != memberScoreVo2) {
                map.put("enablescore",memberScoreVo2.getEnablescore()/10000.0);
                map.put("standbyscore",memberScoreVo2.getStandbyscore()/10000.0);
            }
            logger.info("查询会员积分流水接口入参，pageBean={},scorePageRequest={}", JSON.toJSONString(pageBean),JSON.toJSONString(scorePageRequest));
            Result result = scoreService.getMemberScorePage(pageBean,scorePageRequest);
            logger.info("查询会员积分流水接口返回值，result={}", JSON.toJSONString(result));
            if (null != result && ResultEnum.SUCCESS.getCode().equals(result.getCode())) {
                map.put("scoreList",result.getData());
                map.put("count",result.getCount());
            }

            map.put("pageNum",pageNum);
            map.put("pageSize",pageSize);
        } catch (Exception e) {
            logger.error("查询会员积分流水接口异常,e={}",e);
        }
        return "score/list";
    }

    private MemberScoreVo2 getMemberScore(Long memberId) {
        MemberScoreVo2 memberScoreVo2 = null;
        try {
            logger.info("查询会员积分接口入参，memberId={}", memberId);
            memberScoreVo2 = scoreService.getMemberScore(memberId);
            logger.info("查询会员积分接口返回值，memberScoreVo2={}", JSON.toJSONString(memberScoreVo2));
        } catch (Exception ex) {
            logger.error("查询会员积分接口异常,e={}",ex);
        }
        return memberScoreVo2;
    }
    
    /**
     * 获取会员基本信息
     * @param model
     * @param memberId
     * @param request
     * @return
     */
    @MemberCache
    @RequestMapping(value="/memberInfo",method=RequestMethod.GET)
    public String memberCashPage(Model model,HttpServletRequest request,MemberInfo memberInfo){
    	Result result=memberCashService.getMemberInfo(memberInfo.getId());
    	MemberInfoByCashVo  mv=(MemberInfoByCashVo) result.getData();
    	model.addAttribute("memberInfo", mv);
    	model.addAttribute("msg", result.getMessage());
    	return "score/member";
    }
    /**
     * 会员积分提现
     * @param model
     * @param cv
     * @param request
     * @return
     * @author Mr.Chang
     * 
     */
    @MemberCache
    @RequestMapping(value="/cash",method=RequestMethod.POST)
    public String memberCash(Model model,@ModelAttribute CashVo cv,HttpServletRequest request){
    	String requestIP=IPUtil.getIpAddress(request);//获取ip地址
    	try {
    		Result result=cashService.addMemberCashOrder(cv, requestIP);
    		model.addAttribute("result", result);
		} catch (BizException e) {
			logger.error("会员积分提现异常："+e);
		}
    	return "score/cashResult";
    }
    
  /**
    * 发送短信验证码
	* @Title: sendSmsCode  
	* @Description: 发送短信验证码  
	* @param @param request
	* @param @param phone
	* @param @return    参数  
	* @return Object    返回类型  
	* @throws
	* @author Mr.Chang
	* 
	*/
	@RequestMapping(value="/sendSmsCode",method=RequestMethod.GET)
	@ResponseBody
	public Object sendSmsCode(HttpServletRequest request, Long memberId) {
		logger.info("发送短信验证码会员id: " + memberId);
		Map<String, Object> map = ResultUtil.setResult(false, PsResultEnum.FAIL.getMsg());
		try {
			//查询会员信息
			Result ret=memberCashService.getMemberInfo(memberId);
			if(!StringUtils.isEmpty(ret.getData())){
				MemberInfoByCashVo  mv=(MemberInfoByCashVo) ret.getData();
				Result result = smsCodeSendService.sendSmsCodeByNoMsg(mv.getPhone(), SmsCodeType.MEMBER_CASH.getCodeType());
				logger.info("发送短信验证码 返回数据 Result = {} ", JSON.toJSONString(result));
				if (result != null) {
					if (ResultEnum.SUCCESS.getCode().equals(result.getCode())) {
						ResultUtil.setResult(map, true, "检验成功");
					} else {
						map.put("message", result.getMessage());
					}
				}
			}else{
				map.put("message", "会员不存在");
			}
		} catch (Exception e) {
			logger.error("发送短信验证码 错误", e);
			ResultUtil.setResult(map, false, "服务器繁忙请稍后再试");
		}
		return map;
	}

}
